package com.ytktt.study.week9.task3.rpcfx.server.netty.coder;

import com.ytktt.study.week9.task3.rpcfx.utils.ProtoStuffUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.RequiredArgsConstructor;

/**
 * protostff netty编码器
 *
 * @author ytk
 */
@RequiredArgsConstructor
public class ProtostuffEncoder extends MessageToByteEncoder<Object> {

    private final Class<?> returnType;

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        if (this.returnType.isInstance(msg)) {
            byte[] data = ProtoStuffUtil.serialize(msg);
            out.writeInt(data.length);
            out.writeBytes(data);
        }
    }
}
